iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0

今天來解YKL09(UVA10931):Parity

Parity

https://ithelp.ithome.com.tw/upload/images/20240923/20155574t1isb43VF7.png

這題是dec轉成binary
計算binary總共有幾個1

用mod去解

#include <iostream>
using namespace std;

string dectobin(int I){
	string str= "";
	if(I==0)return "0";
	if(I==1)return "1";
	while(I > 0){
		int md=0;
		md = I % 2;
		I = I / 2;
		
		str = to_string(md) + str;
		}
	return str;
}


int main(){
	int I;
	while(cin >> I){
		string str = dectobin(I);
		if(I == 0) break;
		int count=0;
		
		for(int i=0;i <= str.size();i++ ){
			if(str[i] == '1'){
				count++;
			}
		}
		
		cout << "The parity of " << str << " is " << count << " (mod 2)." << endl;
	}	
	return 0;
}

上一篇
CPE C++ 刷題 Day 8
下一篇
CPE C++ 刷題 Day 10
系列文
CPE C++ 刷題20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言